package com.xeware.chatter.view;

import com.xeware.chatter.model.DFeedTrackedChanges;
import com.xeware.chatter.model.DFeedComments;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.drawable.Drawable;
//import android.content.Intent;
//import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
//import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.Toast;
//import android.widget.AdapterView.OnItemClickListener;

import com.xeware.chatter.R;
import com.xeware.chatter.model.Feed;
import com.xeware.chatter.service.ConnectionManager;
//import com.xeware.chatter.util.StaticInformation;
import com.sforce.soap.partner.PartnerConnection;
import com.sforce.soap.partner.QueryResult;
import com.sforce.soap.partner.SaveResult;
import com.sforce.soap.partner.sobject.SObject;
import com.sforce.ws.ConnectionException;
import com.sforce.ws.bind.XmlObject;

public class FeedListController extends Activity {
	//private static final String TAG = "Feed List Controller";
	private PartnerConnection connection;
	private List<Feed> feeds;

	private Drawable trbackground;
	private boolean tron;
	private int etw;
	
	@Override 
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.feeds);


        EditText et = (EditText) findViewById(R.id.EditText01);
        etw = et.getWidth();
        et.setMinWidth(etw);
        et.setMaxWidth(etw);
        
        TableRow tr = (TableRow) findViewById(R.id.UpdateRow);
        trbackground = tr.getBackground();
        
        TableLayout tl = (TableLayout) findViewById(R.id.TableLayout01);
        tl.removeView(tr);
        tl.getLayoutParams().height = ViewGroup.LayoutParams.WRAP_CONTENT;
        tl.requestLayout();
        tron = false;
        
        connection = ConnectionManager.getConnectionManager().getConnection();
        startSync();
        
        
//    	lv.setOnItemClickListener(new OnItemClickListener() {
//    		public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 	    
//    			Intent myIntent = new Intent(AccountListController.this, VoiceNoteController.class); 
//    			myIntent.putExtra("id", accounts.get(position).getId());
//    			myIntent.putExtra("name", accounts.get(position).getName());
//    	    	startActivity(myIntent);   			
//    		}
//    	});      
    }
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    //MenuInflater inflater = getMenuInflater();
	    //inflater.inflate(R.menu.feed_menu, menu); // disabling sync for now... if menu is needed for other reasons in future, we can re-enable
	    return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	    case R.id.itemSync:
	        startSync();
	        return true;
//	    case R.id.quit:
//	        quit();
//	        return true;
	    default:
	        return super.onOptionsItemSelected(item);
	    }
	}
	
	private List<Feed> getFeeds() {
		List<Feed> feeds = new ArrayList<Feed>();
		QueryResult result = null;
		try {
			result = connection.query("SELECT Id, Type, CreatedDate, CreatedById, CreatedBy.Name, ParentId, Parent.Name, FeedPostId, FeedPost.Body, FeedPost.Title, FeedPost.LinkURL, (SELECT Id, FieldName, OldValue, NewValue FROM FeedTrackedChanges), (SELECT Id, CreatedDate, CreatedById, CreatedBy.Name, CommentBody FROM FeedComments ORDER BY CreatedDate DESC) FROM NewsFeed ORDER BY CreatedDate DESC, Id LIMIT 10");
		} catch (NullPointerException e) {
			//Log.i(TAG, "Invalid connection");
			Feed f = new Feed("Invalid login credentials...\nPlease go back and try again..\nSuggestion: Cut and Paste the security token vs. typing it in.");
			feeds.add(f);
			return feeds;
		} catch (ConnectionException e) {
			//Log.i(TAG, e.getMessage());
			Feed f = new Feed("Error while connecting...");
			feeds.add(f);
			return feeds;
		}
		if (result.getSize() == 0) {
			Feed f = new Feed("No feed posts found...");
			feeds.add(f);
			return feeds;
		}
		
		for (SObject data : result.getRecords()) {
			try {
				Feed a = new Feed();
				String post = "";
				
				String type = (String) data.getField("Type");

				XmlObject cbxml = (XmlObject) data.getField("CreatedBy");
				String author = (String) cbxml.getField("Name");

				XmlObject pbxml = (XmlObject) data.getField("Parent");
				String group = (String) pbxml.getField("Name");

				if (type.equals("TrackedChange")) {
					DFeedTrackedChanges mftc = new DFeedTrackedChanges(data);
					post = mftc.toString();
				} else if(type.equals("LinkPost")) {
					XmlObject dbxml = (XmlObject) data.getField("FeedPost");
					post = (String) dbxml.getField("Body");
					post += "\n"+ (String) dbxml.getField("Title");
					post += "\n"+ (String) dbxml.getField("LinkUrl");
				} else if(type.equals("UserStatus")) {
					author = ""; // b/c author and parent.name ie group will be same...
					XmlObject dbxml = (XmlObject) data.getField("FeedPost");
					post = (String) dbxml.getField("Body");									
				} else {
					XmlObject dbxml = (XmlObject) data.getField("FeedPost");
					post = (String) dbxml.getField("Body");					
				}
				DFeedComments dfc = new DFeedComments(data);

				String comments = dfc.toString();

				String f = group + " -- " + author + " " + post + "\n" + comments;  
				a.setRecord(f);
				feeds.add(a);
			} catch (NullPointerException e) {
				// occurs 1. if feed entry doesn't have a post, 2. other causes unknown...
			}
		}
		return feeds;
	}
	
	public void notifyToast(String mesg) {
		Context context = getApplicationContext();
		int duration = Toast.LENGTH_SHORT;
		Toast toast = Toast.makeText(context, mesg, duration);
		toast.show();
	}
	
	public void onUpdateClick(View v) {
		if (! tron) {
			this.createTR();
			tron = true;
		} else {
	        TableRow tr = (TableRow) findViewById(R.id.UpdateRow);
	        //trid = tr.getId();
	        //trbackground = tr.getBackground();
	        TableLayout tl = (TableLayout) findViewById(R.id.TableLayout01);
	        tl.removeView(tr);
	        tl.getLayoutParams().height = ViewGroup.LayoutParams.WRAP_CONTENT;
	        tl.requestLayout();
	        tron = false;
		}
		return;
	}
	
	public void createTR() {
        TableLayout tl = (TableLayout) findViewById(R.id.TableLayout01);
        TableRow tr = new TableRow(this);
        tr.setLayoutParams(new TableRow.LayoutParams(
        		LayoutParams.FILL_PARENT,
        		LayoutParams.WRAP_CONTENT));
        tr.setId(R.id.UpdateRow);
        tr.setBackgroundDrawable(trbackground);
        
        EditText et = new EditText(this);
        et.setHint(R.string.status);
        et.setLayoutParams(new TableRow.LayoutParams(
        		LayoutParams.FILL_PARENT,
        		LayoutParams.WRAP_CONTENT
        		));
        et.setMaxLines(1);
        et.setId(R.id.EditText01);
        et.setMinWidth(etw);
        et.setMaxWidth(etw);

        tr.addView(et);
		Button b = new Button(this);
		b.setText(R.string.share);
        b.setLayoutParams(new TableRow.LayoutParams(
        		LayoutParams.FILL_PARENT,
        		LayoutParams.WRAP_CONTENT
        		));
		b.setOnClickListener(mOnShareListener);
		b.setGravity(Gravity.CENTER_VERTICAL);
		//b.setFreezesText(true);
        tr.addView(b);
        tl.addView(tr,new TableLayout.LayoutParams(
                LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT));
        //tl.getLayoutParams().height = ViewGroup.LayoutParams.WRAP_CONTENT;
        tl.requestLayout();
        tl.invalidate();
	}
	
	private OnClickListener mOnShareListener = new OnClickListener() {
		public void onClick(View v) {
			FeedListController.this.onShareClick(v);
		}
	};
	
	public void onShareClick(View v) {
		EditText et = (EditText) findViewById(R.id.EditText01);
		String updateText = et.getText().toString();
		if (updateText.length() == 0) {
			notifyToast("Cannot post a blank status!");
			return;
		}
		new UpdateHandler().execute();
		//Log.i(TAG, "Going to send update: "+et.getText().toString());
	}
	
	public void onStartSync(View v) {
		this.startSync(); // handles call from feeds.xml obj
	}
	
	public void startSync() {
		new SyncHandler().execute();
	}
	
	public void updateFeed() {
		ListView lv = (ListView) findViewById(R.id.list);     	
    	lv.setAdapter(new ArrayAdapter<Feed>(this, R.layout.feed_list_item, feeds));
	}
	
	
	private class SyncHandler extends AsyncTask<Void, Void, Void> {
		private ProgressDialog pd = new ProgressDialog(FeedListController.this);
		
		protected void onPreExecute() {  
			pd.setMessage("Syncing..."); 
			pd.setIndeterminate(true);
			pd.setCancelable(false);
			pd.show();  
		}
		 
		@Override
		protected Void doInBackground(Void... unused) {
	        feeds = getFeeds();
			return null;
		}

	    protected void onPostExecute(Void unused) {
	    	updateFeed();
	    	pd.dismiss();
	    }
	}    
	
	private class UpdateHandler extends AsyncTask<Void, Void, Void> {
		private ProgressDialog pd = new ProgressDialog(FeedListController.this);
		private boolean success = false;
		
		protected void onPreExecute() {  
			pd.setMessage("Updating..."); 
			pd.setIndeterminate(true);
			pd.setCancelable(false);
			pd.show();  
		}
		 
		@Override
		protected Void doInBackground(Void... unused) {			
			try {
				EditText et = (EditText) findViewById(R.id.EditText01);
				String updateText = et.getText().toString();
				SObject user = new SObject();
				user.setType("User");
				user.setId(connection.getUserInfo().getUserId());
				user.setField("CurrentStatus", updateText);
				SaveResult[] results = connection.update(new SObject[] { user });
				if (!results[0].isSuccess()) {
					success = false;
				} else {
					success = true;
				}
			} catch (NullPointerException e) {
				success = false;
			} catch (ConnectionException e) {
				success = false;			
			}
			return null;
		}

	    protected void onPostExecute(Void unused) {
	    	pd.dismiss();
	    	if (success) {
	    		notifyToast("Status update posted.");
	    		EditText et = (EditText) findViewById(R.id.EditText01);
	    		et.setText("");
				//startSync();
	    	} else {
	    		notifyToast("Failed to post status update.");
	    	}
	    }
	}    
}
